package cn.akwangl.spring.dependency.lookup;

import cn.akwangl.spring.ioc.model.User;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import java.util.function.Consumer;

/**
 * {@link ObjectProvider} 使用
 *
 * @author youyongkun
 * @date 2021/7/4 11:07
 */
public class ObjectProviderDemo {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.register(ObjectProviderDemo.class);
        applicationContext.refresh();

        lookupByObjectProvider(applicationContext);
        lookupByStreamOps(applicationContext);
        lookupIfAvailable(applicationContext);

        applicationContext.close();
    }


    /**
     * {@link ObjectProvider#stream()} Stream使用
     *
     * @param applicationContext IOC
     * @author youyongkun
     * @date 2021/7/5 10:39
     */
    private static void lookupByStreamOps(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<String> objectProvider = applicationContext.getBeanProvider(String.class);
        objectProvider.stream().forEach(System.out::println);
    }

    /**
     * {@link ObjectProvider#ifAvailable(Consumer)} Java8 lambda扩展
     *
     * @param applicationContext BeanFactory
     * @author youyongkun
     * @date 2021/7/5 10:36
     */
    private static void lookupIfAvailable(AnnotationConfigApplicationContext applicationContext) {
        ObjectProvider<User> userObjectProvider = applicationContext.getBeanProvider(User.class);
        User user = userObjectProvider.getIfAvailable(User::createUser);
        System.out.println("当前 User 对象：" + user);
    }


    @Bean
    @Primary
    public String helloWorld() {
        return "hello,World!";
    }

    @Bean
    public String message() {
        return "Message";
    }

    private static void lookupByObjectProvider(ApplicationContext applicationContext) {
        ObjectProvider<String> objectProvider = applicationContext.getBeanProvider(String.class);
        System.out.printf("ObjectProvider 演示: %s \n", objectProvider.getObject());
    }


}
